<template>
  <div class="column-management-page">
    <el-card>
      <div class="header-info">
        <el-button :icon="ArrowLeftBold" circle @click="goBack" title="返回" />
        <h3>栏位管理</h3>
        <span>当前栋舍类型：{{ currentHouseTypeName }}</span>
      </div>
      <el-button type="danger" size="small" style="margin-bottom: 16px;" @click="onAddColumnClick">新增栏位</el-button>
      <el-table :data="tableData" border style="width: 100%;">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="Field_Name" label="栏位名称" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" text @click="onEditClick(scope.row)">修改</el-button>
            <el-button type="danger" size="small" text @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="pageIndex"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
    <el-dialog :title="isEdit ? '编辑栏位' : '新增栏位'" v-model="dialogVisible" width="500px">
      <el-radio-group v-model="addType" style="margin-bottom: 16px;">
        <el-radio label="single">单个新增</el-radio>
        <el-radio label="batch">批量新增</el-radio>
      </el-radio-group>
      <div style="margin-bottom: 16px;">
        <span>当前栋舍类型：{{ currentHouseTypeName }}</span>
      </div>
      <el-form :model="form" ref="formRef">
        <el-form-item
          v-if="addType === 'single'"
          label="栏位名称"
          prop="Field_Name"
          :rules="[{ required: true, message: '栏位名称不能为空', trigger: 'blur' }]"
        >
          <el-input v-model="form.Field_Name" placeholder="请输入栏位名称" />
        </el-form-item>
        <template v-else>
          <el-form-item label="前缀">
            <el-input v-model="form.Prefix" placeholder="请输入前缀" />
          </el-form-item>
          <el-form-item label="开始编号">
            <el-input v-model="form.Start_number" placeholder="请输入开始编号" type="number" />
          </el-form-item>
          <el-form-item label="栏位数量">
            <el-input v-model="form.Count" placeholder="请输入栏位数量" type="number" />
          </el-form-item>
          <div style="margin: 16px 0 0 0; font-size: 16px;">
            生成栏位：
            <span>
              {{
                form.Prefix && form.Start_number && form.Count
                  ? `${form.Prefix}${form.Start_number} 至 ${form.Prefix}${Number(form.Start_number) + Number(form.Count) - 1}`
                  : '-- 至 --'
              }}
            </span>
          </div>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeftBold } from '@element-plus/icons-vue';
import { Sheep_BreedingRead } from '@/utils/Interceptors';
import { ElMessage } from 'element-plus';
import { Sheep_BreedingWrite } from '@/utils/Interceptors';
import { ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
// 新增栏位相关变量和方法
const dialogVisible = ref(false);
const addType = ref<'single' | 'batch'>('single');
const isEdit = ref(false);
const currentField = ref<{
  Field: number;
  Field_Name: string;
  Prefix: string;
  Start_number: string | number;
  Count: string | number;
  Gen_range: string;
} | null>(null);

const form = ref({
  Field_Name: '',
  Prefix: '',
  Start_number: '',
  Count: '',
  Gen_range: '',
  BuildingId: 0
});
const formRef = ref();

const currentHouseTypeName = ref('');
const tableData = ref([]);
const total = ref(0);
const pageIndex = ref(1);
const pageSize = ref(20);
let buildingId: string | number | null = null;

onMounted(() => {
  currentHouseTypeName.value = route.query.houseTypeName as string || '未知';
  const rawId = route.query.buildingId;
  buildingId = Array.isArray(rawId) ? rawId[0] : rawId;
  if (buildingId) {
    getFieldList();
    form.value.BuildingId = Number(buildingId);
  }
});

function goBack() {
  router.back();
}

function onAddColumnClick() {
  isEdit.value = false;
  dialogVisible.value = true;
  addType.value = 'single';
  form.value = {
    Field_Name: '',
    Prefix: '',
    Start_number: '',
    Count: '',
    Gen_range: '',
    BuildingId: Number(buildingId)
  };
}

function onEditClick(row: any) {
  isEdit.value = true;
  currentField.value = row;
  dialogVisible.value = true;
  addType.value = 'single';
  form.value = {
    Field_Name: row.Field_Name,
    Prefix: row.Prefix ,
    Start_number: row.Start_number ,
    Count: row.Count ,
    Gen_range: row.Gen_range ,
    BuildingId: Number(buildingId)
  };
}

async function getFieldList() {
  const params = {
    BuildingId: Number(buildingId),
    PageIndex: pageIndex.value,
    PageSize: pageSize.value
  };
  const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchField_management', { params });
  if (res.data.code === 200) {
    tableData.value = res.data.PageData;
    total.value = res.data.TotalCount;
  }
}

function handlePageChange(val: number) {
  pageIndex.value = val;
  getFieldList();
}
function handleSizeChange(val: number) {
  pageSize.value = val;
  pageIndex.value = 1;
  getFieldList();
}

async function handleSave() {
  if (addType.value === 'single') {
    if (!form.value.Field_Name || !form.value.Field_Name.trim()) {
      ElMessage.error('栏位名称不能为空');
      return;
    }
  }

  try {
    let res;
    if (isEdit.value && currentField.value) {
      // 编辑模式
      const params = {
        Field: currentField.value.Field,
        BuildingId: Number(buildingId),
        Field_Name: form.value.Field_Name,
        Prefix: form.value.Prefix === 'null' ? '' : form.value.Prefix,
        Start_number: form.value.Start_number === 'null' ? 0 : Number(form.value.Start_number),
        Count: form.value.Count === 'null' ? 0 : Number(form.value.Count),
        Gen_range: form.value.Gen_range === 'null' ? '' : form.value.Gen_range,
        IsDelete: false
      };
      res = await Sheep_BreedingWrite.put('/api/Sheepfarm/UpdateField_management', params);
    } else {
      // 新增模式
      const params = {
        BuildingId: Number(buildingId),
        Field_Name: addType.value === 'single' ? form.value.Field_Name : '',
        Prefix: addType.value === 'batch' ? form.value.Prefix : '',
        Start_number: addType.value === 'batch' ? Number(form.value.Start_number) : 0,
        Count: addType.value === 'batch' ? Number(form.value.Count) : 0,
        Gen_range: ''
      };
      res = await Sheep_BreedingWrite.post('/api/Sheepfarm/CreateField_management', params);
    }

    if (res.data.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功');
      dialogVisible.value = false;
      form.value = {
        Field_Name: '',
        Prefix: '',
        Start_number: '',
        Count: '',
        Gen_range: '',
        BuildingId: Number(buildingId)
      };
      getFieldList();
    } else {
      ElMessage.error(res.data.msg || (isEdit.value ? '修改失败' : '新增失败'));
    }
  } catch (e) {
    ElMessage.error('请求失败');
  }
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(
      `确定要删除栏位"${row.Field_Name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const res = await Sheep_BreedingWrite.delete('/api/Sheepfarm/DeleteField_management', {
      data: {
        Field: row.Field
      }
    });

    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      getFieldList();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
}
</script>

<style scoped>
.column-management-page {
  padding: 20px;
}
.header-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}
.header-info h3 {
  margin: 0;
}
.header-info span {
  font-size: 16px;
  color: #606266;
}
.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style> 